﻿using SuperFx;
using SuperMoney.Datas.DbModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace SuperMoney.Datas
{
	/// <summary>
	/// 
	/// </summary>
	public class CheckInDbService
	{
		/// <summary>
		/// 
		/// </summary>
		public static readonly CheckInDbService Instance = new CheckInDbService();

		/// <summary>
		/// 
		/// </summary>
		/// <param name="deviceId"></param>
		/// <param name="integral"></param>
		public CheckIn Create(string deviceId, int integral)
		{
			if (!DeviceAccountDbService.Instance.Exists(deviceId))
			{
				throw new Exception<BusinessExceptionArgs>("设备账号不存在");
			}

			DateTime checkDay = DateTime.Today;
			if (this.Exists(deviceId, checkDay))
			{
				throw new Exception<BusinessExceptionArgs>("今日已签到");
			}
			using (var db = MRMDB.New())
			{
				CheckIn checkIn = new CheckIn();
				checkIn.DeviceId = deviceId;
				checkIn.CheckDay = checkDay;
				checkIn.CheckTime = DateTime.Now;
				checkIn.Integral = integral;

				db.CheckInSet.Add(checkIn);
				db.SaveChanges();
				return checkIn;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="deviceId"></param>
		/// <param name="checkDay"></param>
		/// <returns></returns>
		public bool Exists(string deviceId, DateTime checkDay)
		{
			checkDay = checkDay.Date;
			using (var db = MRMDB.New())
			{
				return db.CheckInSet.Where(m => m.DeviceId == deviceId && m.CheckDay == checkDay).Count() > 0;
			}
		}
	}
}
